<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
              <el-form-item label="供应日期" style="width: 308px">
                <el-date-picker v-model="queryParams.riQi" type="date"
                                format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
              </el-form-item>

              <el-form-item label="档口" style="width: 308px">
                <el-select v-model="queryParams.dangKouId" placeholder="请选择">
                  <el-option v-for="item in dangKouList" :key="item.id" :label="item.name" :value="item.id" ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="openAdd" >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="primary" icon="Grid" @click="handleExport">导出</el-button>
              </el-col>
            </el-row>

            <el-table v-loading="loading" :data="dataList"
                      highlight-current-row @current-change="handleCurrentChange">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="出库单编号" align="center" prop="id"  />
              <el-table-column label="档口名称" align="center" prop="dangKouName"  />
              <el-table-column label="档口地址" align="center" prop="dangKouDiZhi"  />
              <el-table-column label="货品名称" align="center" prop="huoPinName"  />
              <el-table-column label="出库数量" align="center" prop="chuKuCount" />
              <el-table-column label="出库价格" align="center" prop="chuKuPrice" />
              <el-table-column label="出库时间" align="center" prop="chuKuShiJian" >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.chuKuShiJian) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="openModify(scope.row.id)" >修改与审核</el-button>
                  <el-button link type="primary" icon="Edit" @click="tuiKu(scope.row)" >退入仓库</el-button>
                  <el-button link type="primary" icon="Edit" @click="tuiHuo(scope.row)" >直接退货</el-button>
                </template>
              </el-table-column>

            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <el-dialog :title="title" v-model="showAddDialog" width="80%" append-to-body>
      <el-form :model="editForm" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="name">
              <div v-if="editForm.id === undefined">
                <el-select v-model="editForm.cangKuId" style="width: 240px" @change="onEditCangKuSelected" >
                  <el-option v-for="item in cangKuList" :label="item.name" :value="item.id" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="货品" v-if="editForm.id === undefined">
                <el-select v-model="editForm.huoPinIdList" multiple style="width: 240px" @change="oneHuoPinChange" >
                  <el-option v-for="item in editHuoPinList" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="订单时间" >
              <el-date-picker v-model="editForm.chuKuTime" type="date" value-format="YYYY-MM-DD"
                              @change="onChuKuTimeChange"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="订单货品" >
              <el-table :data="dingDanDetailList" @selection-change="selectDingDanDetail">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column prop="id" label="id" />
                <el-table-column prop="dangKouName" label="档口" />
                <el-table-column prop="huoPinName" label="商品名称" />
                <el-table-column prop="riQi" label="计划日期" />
                <el-table-column prop="shiJian" label="计划时间" />
                <el-table-column label="出库数量" >
                  <template #default="scope">
                    <el-input v-model="scope.row.chuKuCount" type="number"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="出库价格" >
                  <template #default="scope">
                    <el-input v-model="scope.row.chuKuPrice" type="number"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">创建</el-button>
          <el-button @click="showAddDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <el-dialog :title="title" v-model="showEditDialog" width="80%" append-to-body>
      <el-form :model="editForm" label-width="100px">

        <el-row>
          <el-col :span="24">
            <el-form-item label="订单货品" >
              <el-table :data="dingDanDetailList" @selection-change="selectDingDanDetail">
                <el-table-column type="selection" width="50" align="center" />
                <el-table-column prop="id" label="id" />
                <el-table-column prop="dangKouName" label="档口" />
                <el-table-column prop="huoPinName" label="商品名称" />
                <el-table-column prop="chuKuShiJian" label="出库时间" >
                  <template #default="scope">
                    {{ parseTime(scope.row.chuKuShiJian)}}
                  </template>
                </el-table-column>
                <el-table-column label="出库数量" >
                  <template #default="scope">
                    <el-input v-model="scope.row.chuKuCount" type="number"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="出库价格" >
                  <template #default="scope">
                    <el-input v-model="scope.row.chuKuPrice" type="number"></el-input>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitModify()">保存修改</el-button>
          <el-button type="success" @click="submitAudit(1)" v-if="editForm.status === 0">审核通过</el-button>
          <el-button type="warning" @click="submitAudit(2)" v-if="editForm.status === 0">审核驳回</el-button>
          <el-button @click="showEditDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>

<script setup name="RuKuDan">
import useAppStore from '@/store/modules/app'
import {listWithPage,  audit, exportListUrl } from "@/api/system/chukudan.js";
import {listAll as loadAllDangKou} from "@/api/system/dangkou.js";
import {listByCangKu } from "@/api/system/huopin.js";
import {get, post} from '@/api/system/request.js';
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {getToday} from "@/utils/time.js";
import {listUserAll as loadAllCangKu} from "@/api/system/cangku.js";

const router = useRouter();
const appStore = useAppStore()
const { proxy } = getCurrentInstance();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
});
const total = ref(0);
const dataList = ref([]);

const editForm = ref({});
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const loading = ref(true);

const title = ref("");
const editHuoPinList = ref([]);
const dangKouList = ref([]);
const cangKuList = ref([]);

queryParams.value.riQi = getToday();

function initDangKouList(){
  loadAllDangKou().then(res => {
    dangKouList.value = res.data;
  });
}

initDangKouList();


async function getAllCangKu(){
  loading.value = true;

  let res = await loadAllCangKu();
  loading.value = false;
  cangKuList.value = res.rows;
}

getAllCangKu();


async function onEditCangKuSelected(cangKuId) {
  let res = await listByCangKu({cangKuId});
  editHuoPinList.value = res.data;
}

/** 查询列表 */
async function getList() {
  if(queryParams.value.riQi == null && queryParams.value.dangKouId == null){
    proxy.$modal.msgError("日期与档口请至少选择一个")
    return;
  }

  loading.value = true;
  let res = await listWithPage(queryParams.value);

  loading.value = false;
  dataList.value = res.rows;
  total.value = res.total;
}
getList();


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


const dingDanDetailList = ref([]);

/** 新增按钮操作 */
function openAdd() {
  editForm.value = {};
  console.log(editForm.value.id);
  dingDanDetailList.value = [];
  editHuoPinList.value = [];
  showAddDialog.value = true;
  title.value = "新建";
}

/** 编辑按钮操作 */
async function openModify(id) {
  editForm.value = {};
  let rsp = await get("/system/chuKuDan/"+id, {})
  editForm.value = rsp.data;

  console.log(editForm.value);
  dingDanDetailList.value = [];
  dingDanDetailList.value.push(rsp.data);

  title.value = "编辑";
  showEditDialog.value = true;
}

function tuiKu(row){
  proxy.$modal.confirm("确定要进行退库吗，退库表示将货品退回仓库，而不是退货给供应商", "注意！", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then( async () => {
    let rsp = await post("/system/chuKuDan/tuiKu", {id: row.id })
    editForm.value = rsp.data;
    if (rsp.code === 200) {
      proxy.$modal.msgSuccess("退货入库成功");
    } else {
      proxy.$modal.msgSuccess("退货入库失败");
    }
  });

}


function tuiHuo(row){
  proxy.$modal.confirm("确定要进行退货吗，直接退货表示将货品退给供应商，而不是退回仓库", "注意！", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then( async () => {
    let rsp = await post("/system/chuKuDan/tuiHuo", {id: row.id })
    editForm.value = rsp.data;
    if (rsp.code === 200) {
      proxy.$modal.msgSuccess("退货成功");
    } else {
      proxy.$modal.msgSuccess("退货失败");
    }
  });

}


async function onChuKuTimeChange(){
  let rsp = await post("/system/dingDan/getDetailByRiQiAndCaiPin",
      {riQi: editForm.value.chuKuTime, huoPinIdList: editForm.value.huoPinIdList});

  dingDanDetailList.value = rsp.data;
}


function selectDingDanDetail(values) {
  editForm.value.details = values;
}


/** 提交按钮 */
async function submitForm() {
    let rsp = await post("/system/chuKuDan/add", editForm.value);
    if(rsp.code === 200) {
      proxy.$modal.msgSuccess("新建成功");
      showAddDialog.value = false;
      getList();
    } else {
      proxy.$modal.msgWarning(rsp.msg);
    }
}

async function submitModify(){
  editForm.value = dingDanDetailList.value[0];
  let rsp = await post("/system/chuKuDan/update", editForm.value);
  if(rsp.code === 200) {
    proxy.$modal.msgSuccess("修改成功");
    showEditDialog.value = false;
    getList();
  } else {
    proxy.$modal.msgWarning(rsp.msg);
  }
}

async function submitAudit(status){
  let rsp = await audit(editForm.value.id, status);
  if(rsp.code === 200){
    showAddDialog.value = false;
    proxy.$modal.msgSuccess("审核成功");
    getList();
  } else {
    proxy.$modal.msgWarning("审核失败");
  }
}

const currentRowId = ref(0);
function handleCurrentChange(row){
  console.log(row);
  if(row === null){
    currentRowId.value = null;
  } else {
    currentRowId.value = row.id;
  }
}

function handleExport(){
  let id = currentRowId.value;
  console.log(id);
  proxy.download(exportListUrl, {
    id: id
  },`出库单信息-${id}.xlsx`);
}


</script>
